package com.qf.edu.commons.web.exception;

import com.qf.edu.data.base.Codes;
import com.qf.edu.data.base.R;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 全局异常处理 - 捕获所有Exception异常
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R globalHandler(Exception e){
        //记录日志文件
        log.error("【Global Exception】全局异常触发!", e);
        return R.fail();
    }

    /**
     * 自定义业务异常的处理
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public R serviceHandler(ServiceException e){
        //获取业务异常的响应枚举对象
        Codes codes = e.getCodes();
        //返回给客户端
        return R.fail(codes, null);
    }

    /**
     * 实体类参数校验的异常处理
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R entityValiteHandler(MethodArgumentNotValidException e){
        List<String> errorInfos = e.getBindingResult()
                .getAllErrors().stream()
                .map(objectError -> objectError.getDefaultMessage())
                .collect(Collectors.toList());

        return R.fail(Codes.VAILTE_ERROR, errorInfos);
    }

    /**
     * 形参的参数校验异常
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R paramsValdateHandler(ConstraintViolationException e){
        List<String> result = e.getConstraintViolations().stream()
                .map(constraintViolation -> constraintViolation.getMessage())
                .collect(Collectors.toList());
        return R.fail(Codes.VAILTE_ERROR, result);
    }
}
